package com.xz.apply.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.apply.domain.PurchaseApply;
import com.xz.apply.domain.PurchaseProductApply;
import com.xz.apply.mapper.PurchaseApplyMapper;
import com.xz.apply.service.IPurchaseApplyService;
import com.xz.apply.service.IPurchaseProductApplyService;
import com.xz.apply.vo.ConfirmPurchaseApplyVo;
import com.xz.apply.vo.PurchaseApplyInfoVo;
import com.xz.apply.vo.PurchaseApplyVo;
import com.xz.apply.vo.PurchaseProductApplyVo;
import com.xz.common.annotation.DataScope;
import com.xz.common.config.XzConfig;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.redis.RedisCache;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.diagnosis.vo.SalesPurchaseApplyVo;
import com.xz.product.service.IProductService;
import com.xz.product.vo.ProductCategoryVo;
import com.xz.purchase.domain.PurchaseProductParam;
import com.xz.sales.domain.SalesOrderDetail;
import com.xz.warehouse.service.IWarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 采购申请Service业务层处理
 *
 * @author xz
 * @date 2024-01-19
 */
@Service
public class PurchaseApplyServiceImpl extends ServiceImpl<PurchaseApplyMapper, PurchaseApply> implements IPurchaseApplyService {
    @Autowired
    private PurchaseApplyMapper purchaseApplyMapper;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IPurchaseProductApplyService iPurchaseProductApplyService;
    @Autowired
    private IWarehouseService iWarehouseService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询采购申请
     *
     * @param id 采购申请主键
     * @return 采购申请
     */
    @Override
    public PurchaseApplyInfoVo selectPurchaseApplyById(Long id) {
        PurchaseApplyInfoVo purchaseApplyInfoVo = purchaseApplyMapper.selectPurchaseApplyById(id);
        if(Objects.nonNull(purchaseApplyInfoVo)){
            List<PurchaseProductApplyVo> productApplyVoList = purchaseApplyInfoVo.getProductApplyVoList();
            for(PurchaseProductApplyVo productApplyVo :productApplyVoList){
                List<PurchaseProductParam> purchaseProductParamList =new ArrayList<>();
                String productParam = productApplyVo.getProductParam();
                if(Objects.nonNull(productParam)){
                    List<String> list = Arrays.asList(productParam.split(";"));
                    for(String params:list){
                        String[] split = params.trim().split(":");
                        if(split.length==2){
                            PurchaseProductParam purchaseProductParam=new PurchaseProductParam();
                            purchaseProductParam.setAttributeName(split[0].trim());
                            purchaseProductParam.setAttributeParameter(split[1].trim());
                            purchaseProductParamList.add(purchaseProductParam);
                        }
                    }
                }
                productApplyVo.setPurchaseProductParamList(purchaseProductParamList);
            }
        }
        return purchaseApplyInfoVo;
    }

    /**
     * 查询采购申请列表
     *
     * @param purchaseApply 采购申请
     * @return 采购申请
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<PurchaseApplyVo> selectPurchaseApplyList(PurchaseApply purchaseApply) {
        return purchaseApplyMapper.selectPurchaseApplyList(purchaseApply);
    }

    /**
     * 确定采购申请列表
     *
     * @param purchaseApply 采购申请
     * @return 采购申请
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<ConfirmPurchaseApplyVo> confirmPurchaseApplyList(PurchaseApply purchaseApply) {
      List<ConfirmPurchaseApplyVo> vos = purchaseApplyMapper.confirmPurchaseApplyList(purchaseApply);
      if(CollectionUtils.isEmpty(vos)){
        return vos;
      }
      // 根据产品id填充最后一次确认的供应商id
      String key = XzConfig.getRedisPrefix() + "applyreorder:lastsupplier:" + SecurityUtils.getUserId();
      Map<String,String> map = redisCache.getCacheMap(key);
      if(!CollectionUtils.isEmpty(map)){
        vos.forEach(vo->{
          if(null != vo.getProductId() && null == vo.getSupplierId()){
            String supplierId = map.get(""+vo.getProductId());
            if(!StringUtils.isEmpty(supplierId)){
              vo.setSupplierId(Long.valueOf(supplierId));
            }
          }
        });
      }
      //缓存此次提交的数据中，最后一笔的供应商id
      saveRedisLastSupplierForApply(vos);
      return vos;
    }

  /**
   * 缓存此次提交的数据中，最后一笔的供应商id，名称
   * @param reorderInfoDtoList
   */
  private void saveRedisLastSupplierForApply(List<ConfirmPurchaseApplyVo> reorderInfoDtoList) {
    // 用户提了个需求：定制采购确认的供应商，默认该商品上次入库的供应商，如没有入库过，则为空。
    // 所以这里要缓存此次提交的数据中，最后一笔的供应商id，名称，以便于前端为下一次要提交的数据赋值“供应商”
    String key = XzConfig.getRedisPrefix() + "applyreorder:lastsupplier:" + SecurityUtils.getUserId();
    Map<String,String> map = new HashMap();
    reorderInfoDtoList.forEach(info->{
      if(null != info.getProductId() && null != info.getSupplierId()){
        map.put(""+info.getProductId(),""+info.getSupplierId());
      }
    });
    redisCache.setCacheMap(key, map);
  }

    /**
     * 新增采购申请
     *
     * @param purchaseApply 采购申请
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertPurchaseApply(PurchaseApply purchaseApply) {
        List<PurchaseProductApply> productApplyList = purchaseApply.getProductApplyList();
        if(CollectionUtils.isEmpty(productApplyList)){
            return AjaxResult.error("商品不能为空");
        }
        purchaseApply.setApplyNumber(RedisCode.getCode("CGSQ"));
        // 默认状态为：采购未提单
        purchaseApply.setPurchaseStatus(1);
        // 非业务字段赋值
        purchaseApply.setCreateTime(DateUtils.getNowDate());
        purchaseApply.setCreateBy(SecurityUtils.getUserId());
        purchaseApply.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        // 新增[采购申请单]
        int insertPurchase = purchaseApplyMapper.insertPurchaseApply(purchaseApply);
        if(insertPurchase>0){
            // 新增[采购申请单]中的商品
            savePurchaseProductApply(productApplyList,purchaseApply);
        }
        return insertPurchase>0? AjaxResult.success("新增成功"):AjaxResult.error("新增失败");
    }

    /**
     * 新增采购申请
     *
     * @param salesPurchaseApplyVo 采购申请
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addSalesPurchaseApply(SalesPurchaseApplyVo salesPurchaseApplyVo) {
        PurchaseApply purchaseApply = new PurchaseApply();
        List<SalesOrderDetail> orderDetailList = salesPurchaseApplyVo.getOrderDetailList();
        if(CollectionUtils.isEmpty(orderDetailList)){
            return 0;
        }else {
            int sum = orderDetailList.stream().mapToInt(SalesOrderDetail::getSellingNum).sum();
            purchaseApply.setApplyNum(sum);
        }

        purchaseApply.setApplyNumber(RedisCode.getCode("CGSQ"));
        purchaseApply.setCreateTime(DateUtils.getNowDate());
        purchaseApply.setCreateBy(SecurityUtils.getUserId());
        purchaseApply.setDeptId(salesPurchaseApplyVo.getSalesDeptId());
        purchaseApply.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        purchaseApply.setPurchaseStatus(1);
        purchaseApply.setProductApplyType(3);
        purchaseApply.setStatus(2);
        purchaseApply.setBizId(salesPurchaseApplyVo.getSalesOrderId());
        purchaseApply.setBizNo(salesPurchaseApplyVo.getSalesNo());
        int insertPurchase = purchaseApplyMapper.insertPurchaseApply(purchaseApply);
        if(insertPurchase>0){
            List<PurchaseProductApply> productApplyList = new ArrayList<>();
            orderDetailList.stream().forEach(i->{
                PurchaseProductApply product = new PurchaseProductApply();
                product.setPurchaseId(purchaseApply.getId());
                product.setProductParam(i.getProductParam());
                product.setProductName(i.getProductName());
                product.setStatus(1);
                product.setDeptId(salesPurchaseApplyVo.getSalesDeptId());
                product.setTenantId(purchaseApply.getTenantId());
                product.setCreateBy(purchaseApply.getCreateBy());
                product.setCreateTime(DateUtils.getNowDate());
                product.setProductId(i.getProductId());
                product.setCostPrice(i.getSellingPrice());
                product.setApplyNum(i.getSellingNum());

                product.setProductUrlName(i.getFileName());
                product.setProductUrl(i.getFileUrl());

                product.setRemark(i.getRemark());
                product.setBizDetailId(i.getId());
                ProductCategoryVo productCategory = iProductService.getProductCategory(i.getProductId());
                if(Objects.nonNull(productCategory)){
                    product.setBrandName(productCategory.getBrandName());
                    product.setProdName(productCategory.getProdName());
                    product.setProductCategory(productCategory.getProductCategory());
                    product.setProductEncoded(productCategory.getEncoded());
                }
                productApplyList.add(product);
            });
            iPurchaseProductApplyService.saveBatch(productApplyList);
        }
        return insertPurchase;
    }

    /**
     * 保存采购申请的商品数据
     * @param productApplyList
     * @param purchase
     */
    public void savePurchaseProductApply(List<PurchaseProductApply> productApplyList, PurchaseApply purchase) {
        productApplyList.stream().forEach(productApply -> {
            productApply.setPurchaseId(purchase.getId());
            productApply.setWarehouseId(purchase.getWarehouseId());
            productApply.setWarehouseName(purchase.getWarehouseName());
            // 如果是门店申请
            if (purchase.getProductApplyType() == 1) {
                // 则需要拼接前端传入的（“采购商品属性”列表中）各个商品属性的属性名称
                StringBuilder stringBuilder = new StringBuilder();
                productApply.getPurchaseProductParamList().forEach(j -> {
                    stringBuilder.append(j.getAttributeName() + ":" + j.getAttributeParameter() + ";");
                });
                // 设为商品参数字段
                productApply.setProductParam(stringBuilder.toString());
            }
            // 检索商品id对应的各项商品属性字段值，然后填充品牌名称，产品名称，商品类别
            ProductCategoryVo productCategory = iProductService.getProductCategory(productApply.getProductId());
            if (Objects.nonNull(productCategory)) {
                productApply.setBrandName(productCategory.getBrandName());
                productApply.setProdName(productCategory.getProdName());
                productApply.setProductCategory(productCategory.getProductCategory());
            }
            // 默认状态为：未提单
            productApply.setStatus(1);
            // 非业务字段赋值
            productApply.setDeptId(purchase.getDeptId());
            productApply.setTenantId(purchase.getTenantId());
            productApply.setCreateBy(purchase.getCreateBy());
            productApply.setCreateTime(DateUtils.getNowDate());
        });
        boolean saveBatch = iPurchaseProductApplyService.saveBatch(productApplyList);
        if (!saveBatch) {
            throw new ServiceException("新增失败");
        }
    }
    /**
     * 修改采购申请
     *
     * @param purchaseApply 采购申请
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updatePurchaseApply(PurchaseApply purchaseApply) {
        if(purchaseApply.getId()==null){
            return AjaxResult.error("参数id不能为空");
        }
        List<PurchaseProductApply> productApplyList = purchaseApply.getProductApplyList();
        if(CollectionUtils.isEmpty(productApplyList)){
            return AjaxResult.error("商品不能为空");
        }
        // 非业务字段赋值
        purchaseApply.setUpdateTime(DateUtils.getNowDate());
        purchaseApply.setUpdateBy(SecurityUtils.getUserId());
        // 更新[采购申请单]
        int updatePurchase = purchaseApplyMapper.updatePurchaseApply(purchaseApply);
        if(updatePurchase>0){
            // 根据[采购申请单id]删除对应的[采购申请单商品]
            iPurchaseProductApplyService.deletePurchaseProductApplyById(purchaseApply.getId());
            // 新增[采购申请单]中的商品
            savePurchaseProductApply(productApplyList,purchaseApply);
        }
        return updatePurchase>0? AjaxResult.success("修改成功"):AjaxResult.error("修改失败");
    }

    /**
     * 批量删除采购申请
     *
     * @param ids 需要删除的采购申请主键
     * @return 结果
     */
    @Override
    public int deletePurchaseApplyByIds(Long[] ids) {
        return purchaseApplyMapper.deletePurchaseApplyByIds(ids);
    }

    /**
     * 删除采购申请信息
     *
     * @param id 采购申请主键
     * @return 结果
     */
    @Override
    public int deletePurchaseApplyById(Long id) {
        return purchaseApplyMapper.deletePurchaseApplyById(id);
    }

    /**
     * 采购申请转订单列表
     * @param idList
     * @return
     */
    @Override
    public List<ConfirmPurchaseApplyVo> reorderPurchaseApplyList(List<Long> idList) {
        return baseMapper.reorderPurchaseApplyList(idList);
    }
    /*采购申请详情（采购申请单号）*/
    @Override
    public PurchaseApply getPurchaseApply(String applyNumber) {
        return baseMapper.getPurchaseApply(applyNumber);
    }
}
